#include "YUVImage.h"
#include "base/YUVImage.h"
#include <memory>
#include <iostream>
#include <fstream>
#include <stdint.h>


namespace Sivin {
  YUVImage::YUVImage() {
  }

  YUVImage::YUVImage(int width, int height, Format fmt) {
    mWidth = width;
    mHeight = height;
    mFormat = fmt;
  }

  YUVImage::~YUVImage() {
    if (mYData != nullptr) {
      delete[] mYData;
      mYData = nullptr;
    }

    if (mUData != nullptr) {
      delete[] mUData;
      mVData = nullptr;
    }

    if (mVData != nullptr) {
      delete[] mVData;
      mVData = nullptr;
    }
  }


  std::unique_ptr<YUVImage> YUVImage::loadImage(std::string path, int width, int height, Format format) {
    std::unique_ptr<YUVImage> image = std::unique_ptr<YUVImage>(new YUVImage());
    int size = width * height;
    if (size == 0) {
      return image;
    }
    char *y_Data = nullptr;
    char *u_Data = nullptr;
    char *v_Data = nullptr;
    std::fstream yuvFile;
    yuvFile.open(path, std::fstream::in | std::fstream::binary);
    if (yuvFile.is_open()) {
      y_Data = new char[size];
      u_Data = new char[size / 4];
      v_Data = new char[size / 4];
      yuvFile.read(y_Data, size);

      yuvFile.read(u_Data, size / 4);

      yuvFile.read(v_Data, size / 4);
    } else {
      std::cout << "open yuv file failed\n";
    }
    yuvFile.close();

    image->mYData = y_Data;
    image->mUData = u_Data;
    image->mVData = v_Data;

    image->mWidth = width;
    image->mHeight = height;
    image->mFormat = format;

    return image;
  }

}// namespace Sivin